package slxy.jiangtao.dts.controller.business;

import com.alibaba.fastjson.JSON;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import slxy.jiangtao.dts.controller.BaseController;
import slxy.jiangtao.dts.core.common.bean.Constants;
import slxy.jiangtao.dts.core.common.bean.JSONResult;
import slxy.jiangtao.dts.core.common.service.CommonService;
import slxy.jiangtao.dts.entity.business.Email;
import slxy.jiangtao.dts.entity.business.Notice;
import slxy.jiangtao.dts.entity.business.UserEmail;
import slxy.jiangtao.dts.service.sys.EmailService;
import slxy.jiangtao.dts.service.sys.UserService;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Code must be sexy
 * Created by Jiang Tao on 2017/5/26.
 * 说明：邮件发送controller
 */
@Controller
@RequestMapping("email")
public class EmailController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(EmailController.class);
    @Autowired
    CommonService commonService;
    @Autowired
    EmailService emailService;
    @Autowired
    UserService userService;

    /**
     * 邮件加载index页面，默认加载收件
     */
    @RequestMapping("index")
    public String index(ModelMap modelMap, HttpServletRequest request) {
        //默认首次加载收件箱所有内容
        /*String sql = "SELECT count(*) FROM user_email u JOIN email e on u.email_id = e.id WHERE u.receiver =" + getUserInSession(request).getId();
        int count = Integer.parseInt(commonService.getCountForJdbc(sql).toString());*/
        List<Map> emails = emailService.getInEmails(getUserInSession(request).getId());
        /*Page page = new Page(emails, Constants.DEFAULT_PAGE_SIZE,Constants.DEFAULT_CURRENT_PAGE,count);*/
        modelMap.put("emails", JSON.toJSONString(emails));
        return "email/index";
    }

    /**
     * 获取所有收件
     */
    @RequestMapping(value = "inmails", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult inmails(HttpServletRequest request) {
        List<Map> emails = emailService.getInEmails(getUserInSession(request).getId());
        return JSONResult.success(emails);
    }

    /**
     * 查看所有发出邮件
     */
    @RequestMapping(value = "outmails", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult outmails(HttpServletRequest request) {
        List<Map> emails = emailService.getOutEmails(getUserInSession(request).getId());
        return JSONResult.success(emails);
    }

    /**
     * 查看邮件内容
     */
    @RequestMapping("detail/{emailid}")
    public String detail(@PathVariable Integer emailid, ModelMap modelMap, HttpServletRequest request) {
        Email email = commonService.get(Email.class, emailid);

        //查询邮件时在user_email中设置已读   start
        DetachedCriteria dc = DetachedCriteria.forClass(UserEmail.class);
        dc.add(Restrictions.eq("receiver", getUserInSession(request).getId()));
        dc.add(Restrictions.eq("emailId", emailid));
        List<UserEmail> userEmails = commonService.findByDetached(dc);
        Optional.ofNullable(userEmails).ifPresent(
                userEmailList ->
                        userEmailList.forEach(
                                userEmail -> {
                                    if (userEmail.getState() == Constants.EMAIL_UNREAD) {
                                        userEmail.setState(Constants.EMAIL_READ);
                                        commonService.updateEntity(userEmail);
                                    }
                                }
                        )
        );
        //end

        modelMap.put("email", email);
        return "email/detail";
    }

    /**
     * 邮件添加或编辑跳转页面
     */
    @RequestMapping("page/{forword}")
    public String Page(ModelMap modelMap, @PathVariable String forword, HttpServletRequest request) {
        if (forword.trim().equals("update")) {
            Integer id = Integer.parseInt(request.getParameter("id"));
            modelMap.put("email", commonService.get(Email.class, id));
        }
        return "email/" + forword.trim().toLowerCase();
    }

    @RequestMapping("submit/{method}")
    @ResponseBody
    public JSONResult submit(@PathVariable String method, Email email, HttpServletRequest request) {
        Integer id = email.getId();
        try {
            if (method.trim().equals("add") || method.trim().equals("update")) {
                id = emailService.addOrUpdate(email, getUserInSession(request));
            } else {
                return JSONResult.failure("无效访问路径");
            }
        } catch (Exception e) {
            logger.error("邮件操作失败", e);
            return JSONResult.failure("操作失败");
        }
        return JSONResult.success(id);
    }

    /**
     * 删除一个邮件
     */
    @RequestMapping("delete/{emialid}")
    @ResponseBody
    public JSONResult delete(@PathVariable Integer emialid, HttpServletRequest request) {
        try {
            emailService.delete(emialid, getUserInSession(request));
        } catch (Exception e) {
            logger.error("邮件删除失败", e);
            return JSONResult.failure("邮件删除失败");
        }
        return JSONResult.success();
    }

    @RequestMapping("chooseReceiverPage/{emailid}")
    public String chooseReceiver(@PathVariable Integer emailid, ModelMap modelMap, HttpServletRequest request) {
        modelMap.put("emailId", emailid);
        modelMap.put("treeNode", JSON.toJSON(userService.userDepartZtree()));
        return "email/chooseReceiverPage";
    }

    @RequestMapping(value = "send", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult send(Integer[] users, @RequestParam Integer emailId, HttpServletRequest request) {
        if (users.length < 1) {
            return JSONResult.failure("收件人不能为空");
        }
        Email email = commonService.get(Email.class, emailId);
        try {
            emailService.insertUserEmail(emailId,users,getUserInSession(request).getId());
            emailService.sendEmail(email.getContent(), email.getName(), users, getUserInSession(request).getName());
            email.setState(Constants.EMAIL_SENDED);
            commonService.updateEntity(email);
        } catch (Exception e) {
            logger.error("发送邮件失败", e);
            return JSONResult.failure("发送邮件失败");
        }
        return JSONResult.success();
    }

}
